<?php
/**
 * @fileoverview
 * 用户相关功能的Controller。
 * 本Controller定义了所有与用户相关的功能，包括：
 *   1. 用户登录
 *   2. 查看用户的个人首页
 *   3. 修改个人信息
 *   4. 修改密码
 *   5. 查看所有用户一览
 *   6. 注销
 *   7. 新用户加入申请
 */
class FundlogsController extends AppController {


	function beforeFilter() {
		$this->checkLogin();
	}

	/**
	 * 查看收支记录列表
	 * @params {int} $days 显示天数
	 */
	function index($days = 7) {

		$this->layout = 'private';

		$fundlogs = $this->Fundlog->findLastNDays($days);
		$this->set('fundlogs', $fundlogs);
		$this->set('days', $days);
		$this->set('perms', $this->userPerms);
	}


	/**
	 * 添加新的收支记录
	 */
	function add() {

		$this->layout = 'internal';
		if (!empty($this->data)) {
			
			$log = $this->data;

			// 填写当前用户的id
			$log['Fundlog']['user_id'] = $this->userId;

			// 计算基金的余额
			$last = $this->Fundlog->findLastLog();
			if (count($last) == 0) {
				$balance = 0;
			} else {
				$balance = $last[0]['Fundlog']['balance'];
			}

			if ($log['Fundlog']['type'] == 'income') {
				$log['Fundlog']['balance'] = $balance + $log['Fundlog']['amount'];
			} else {
				$log['Fundlog']['balance'] = $balance - $log['Fundlog']['amount'];
			}

			if ($this->Fundlog->save($log)) {
				$this->redirect('/fundlogs/');
				exit;
			}
		}
	}
}
